`timescale 1ns / 1ps
`include "InstrHeader.h"
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    09:38:50 07/09/2019 
// Design Name: 
// Module Name:    XALU 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module XALU(
    input Clk,
    input Clr,
    input [`InstrBusWidth] InstrBus,
	
    input [31:0] XALU_A,
    input [31:0] XALU_B,
    output reg [31:0] XALU_HI,
    output reg [31:0] XALU_LO,

    output XALU_Busy
    );


	assign	{`InstrBusWireSet}	=	InstrBus;
	reg MulSel;
	wire [1:0] WriteEnable = {mthi,mtlo};
	
	
	assign	XALU_Busy = MulSel ? Mul_Busy:Div_Busy; 	
	
	initial begin
		MulSel=0;
	end
	
	
	///***
	wire XALU_Start = (mult|multu|div|divu);
	///***
	
	//////////////////////////////////////////////
	/*module DivCore(
    input	Clk,
	input	sign,
    input [31:0] A,
    input [31:0] B,
	input	start,

	output	DataOK,
	output	[31:0]	HI,
	output	[31:0]	LO,
	output	Busy
    );*/
	
	
	wire Div_Busy,Div_OK;
	wire [31:0] Div_HI,Div_LO;
	wire XALU_sign = (mult|div);
	

	DivCore DivCore(
		.Clk(Clk),
		.sign(XALU_sign),
		.A(XALU_A),
		.B(XALU_B),
		.start(XALU_Start),

		.DataOK(Div_OK),
		.HI(Div_HI),
		.LO(Div_LO),
		.Busy(Div_Busy)
	);
	
	
	/*module MultCore(
	input	Clk, 
	input	[31:0]	A, 
	input	[31:0]	B, 
	output	[31:0]	HI,
	output	[31:0]	LO,
	input	start, 
	input	sign,
	output	DataOk,
	output	Busy
    );*/
	wire [31:0] Mul_HI,Mul_LO;
	wire Mul_Busy,Mult_OK;
	MultCore MultCore(
		.Clk(Clk),
		.A(XALU_A),
		.B(XALU_B),
		.HI(Mul_HI),
		.LO(Mul_LO),
		.start(XALU_Start),
		.sign(XALU_sign),
		.DataOK(Mult_OK),
		.Busy(Mul_Busy)
	);
	/////////////////////////////////////////////
	
	
	
	always@(posedge Clk) begin
		
		if(!Clr && XALU_Start) begin
			if(mult) begin
				MulSel <= 1;	
			end
			if(multu) begin
				MulSel <= 1;
			end
			if(div) begin
				MulSel <= 0;
			end
			if(divu) begin
				MulSel <= 0;
			end
		end
		XALU_HI	<=	mthi				?	XALU_A:
					MulSel && Mult_OK	?	Mul_HI:
					Div_OK				?	Div_HI:
											XALU_HI;
		XALU_LO	<=	mtlo				?	XALU_A:
					MulSel && Mult_OK	?	Mul_LO:
					Div_OK				?	Div_LO:
											XALU_LO;
	end
	
	
endmodule
